package com.websystique.springsecurity.service;

import com.websystique.springsecurity.model.User;
import com.websystique.springsecurity.model.UserProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import org.springframework.security.core.GrantedAuthority;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import com.websystique.springsecurity.model.UserProfile;
@Service("customUserDetailsService")
public class CustomUserDetailsService
implements UserDetailsService{

    @Autowired
    private UserService userService;

    @org.springframework.transaction.annotation.Transactional
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.findBySso(username);
        System.out.println("User : "+user.toString());
        if(null==user){throw new UsernameNotFoundException("Username not found");  }
        return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
                user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user));
    }

    private List<GrantedAuthority> getGrantedAuthorities(User user){
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        for(UserProfile userProfil : user.getUserProfiles()){
            System.out.println("UserProfile : "+userProfil);
            authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfil.getType()));
        }
        System.out.print("authorities :"+authorities);
        return authorities;
    }
}
